<?php
if (!defined('__COLA_DIR__')) exit;

/**
 * 编辑页面组件
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Contents_Page_Edit extends Widget_Abstract_Contents implements Widget_Interface_Do
{
    /**
     * 获取当前时间
     *
     * @access protected
     * @return Date
     */
    protected function ___date()
    {
        return new Date();
    }

    /**
     * 获取页面偏移的URL Query
     *
     * @access protected
     * @param integer $created 创建时间
     * @param string $status 状态
     * @return string
     */
    protected function getPageOffsetQuery($cid)
    {
        return 'page=' . $this->getPageOffset('cid', $cid, 'page', 
		'on' == $this->request->all ? 0 : $this->user->uid);
    }

    /**
     * 执行函数
     *
     * @throws Widget_Exception
     */
    public function execute()
    {
        /** 必须为编辑以上权限 */
        $this->user->pass('editor');

        /** 获取文章内容 */
        if (!empty($this->request->cid) && 'delete' != $this->request->do) {
            $this->select()
                ->where('table.contents.cid = ?', $this->request->cid)
			    ->where('table.contents.type = ?', 'page')
                ->limit(1)
			    ->fetchRow(array($this, 'push'));

            if (!$this->have()) {
                throw new Widget_Exception(_t('文章不存在'), 404);
            } else if ($this->have() && !$this->allow('edit')) {
                throw new Widget_Exception(_t('没有编辑权限'), 403);
            }
        }
    }
	
    /**
     * 生成表单
     *
     * @access public
     * @param string $action 表单动作
     * @return Form
     */
    public function form()
    {
        /** 构建表格 */
        $form = new Form($this->security->actionUrl('contents-page-edit', false));

        /** 标题 */
        $title = new Form_Text('title', NULL, NULL, _t('标题'));
        $form->addInput($title);
		
        /** 网址缩略名 */
        $alias = new Form_Text('alias', NULL, NULL, _t('网址缩略名'));
        $form->addInput($alias);

        /** 分类描述 */
        $text =  new Form_Textarea('text', NULL, NULL, _t('文章内容'));
        $form->addInput($text);
		$text->input->setAttr('style', 'min-height: 240px;');

        /** 文章 */
        $intro =  new Form_Textarea('intro', NULL, NULL, _t('摘要'));
        $form->addInput($intro);
		$intro->input->setAttr('style', 'min-height: 120px;');
		
        $options = array();
        $options[] =  _t('不选择');
        $options += $this->getTemplates();
        $template = new Form_Select('template', $options, $this->template, _t('自定义模板'),
        _t('如果你为此页面选择了一个自定义模板, 系统将按照你选择的模板文件展现它.'));
        $form->addInput($template);

		/** 文章图标 */
        $pic = new Form_Text('pic', NULL, NULL, _t('文章图标'), '<label class="btn btn-light btn-sm cola-upload"><i class="fe fe-upload mr-2"></i><span>上传</span><input type="file" accept="image/*" name="file"></label>');
        $form->addInput($pic);
		
        $allowComment = new Form_Checkbox('allowComment', array('1'=>'允许评论'), 1, _t('评论权限'));
        $form->addInput($allowComment);

        /** 动作 */
        $do = new Form_Hidden('do');
        $form->set($do);

        /** 主键 */
        $cid = new Form_Hidden('cid');
        $form->addInput($cid);

        /** 提交按钮 */
        $submit = new Form_Submit();
        $form->addInput($submit);

        if ($this->cid) {
            /** 更新模式 */
            $title->value($this->title);
            $alias->value($this->alias);
			$text->value($this->text);
			$intro->value($this->intro);
			$allowComment->value($this->allowComment);
			$template->value($this->template);
            $do->value('update');
            $cid->value($this->cid);
            $pic->value($this->pic);
		    $pic->input->set($this->pic ? '<br><img style="margin: 5px 0;" class="cola-pic" src="'.$this->icon .'" />' : '', 'html');
            $submit->value(_t('更新文章'));
        } else {
            $do->value('insert');
            $submit->value(_t('发布文章'));
        }

		/** 默认上传js (可覆盖或修改) */
        $this->widget('Widget_Scripts')->set("
            (function () {
                $(document).ready(function () {
var jform = $(\"form\");					
jform.on('change', 'input[type=\"file\"]', function(e) {
	var jthis = $(this);
	var jdiv = jthis.parent().parent().parent();
	var jinput = jdiv.find('input[name=\"pic\"]');
	var cid = jform.find('input[name=\"cid\"]').val();
    $.ajax({
		url: '".$this->security->actionUrl('upload', false)."',
        files: jthis,
        iframe: true,
		data: {id:cid, type:'page'},
		processData: false,
		dataType: 'text',
		cache:false,
		beforeSend: function(s){
			jdiv.find('.cola-upload span').html('正在上传...');
		},
		success: function(s){
		    s = (new Function(\"return \" + s))(); 
		    if(typeof s.code != 'undefined') {
			    if(s.code == 0) {
					if(!$('img', jdiv).length){
						jinput.after('<br><img style=\"margin: 5px 0;\" class=\"cola-pic\" src=\"".$this->options->uploadUrl ."' + s.data.filePath+'?'+Math.random() + '\"/>');
						
					}else{
						$('img', jdiv).attr('src', '".$this->options->uploadUrl ."' + s.data.filePath+'?'+Math.random());
					}
					jinput.val(s.data.filePath);
			    } else {
				   alert(s.msg);
			    }
		    } else {
			    alert(s);
		    }
		},
		complete: function(s){
			jdiv.find('.cola-upload span').html('上传');
		},
    });
});			

});
})();", 'page@upload');
		
		/** 插件接口 */
		//HOOK PLUG_Page_Form($form, $this);
		
		return $form;

    }

    /**
     * 输出文章发布日期
     *
     * @access public
     * @param string $format 日期格式
     * @return void
     */
    public function date($format = NULL)
    {
        if (isset($this->created)) {
            parent::date($format);
        } else {
            echo date($format, $this->options->time + $this->options->timezone - $this->options->serverTimezone);
        }
    }

    /**
     * 获取文章权限
     *
     * @return bool
     */
    public function allow($permission)
    {
        if ('edit' == $permission) {
            $allow = ($this->user->pass('editor', true) || $this->uid == $this->user->uid);
        } else {
            $permission = 'allow' . ucfirst($permission);
            $allow = (isset($this->{$permission}) ? $this->{$permission} : false);
        }		
        return $allow;
    }

    /**
     * 获取网页标题
     *
     * @access public
     * @return string
     */
    public function getMenuTitle()
    {
        return $this->have() ? _t('编辑 %s', $this->title) : _t('增加独立页面');
    }

    /**
     * 发布文章
     *
     * @access public
     * @return void
     */
    public function insertPage($values = array())
    {
        /** 插件接口 */
		//HOOK $values | PLUG_Page_Insert($values, $this);

        /** 发布一个新内容 */
        $insertId = $this->insert($values);

        if ($insertId > 0) {

            /** 更新内容数 */
		    !empty($values['uid']) && $this->db->update('table.users')
		        ->where('uid = ?', $values['uid'])
				->expression('contentsNum', 'contentsNum + 1')
				->affectedRows();

            /** 同步附件 */
            list($images, $files) = $this->widget('Widget_Attachs_Edit')->sync('page', $insertId);
		    $this->update($insertId, array('imagesNum' => $images, 'filesNum' => $files));
        
		    /** 压入数据 */
            $this->select()
			    ->where('table.contents.cid = ?', $insertId)
				->limit(1)
				->fetchRow(array($this, 'push'));
				
            /** 插件接口 */
            //HOOK PLUG_Page_Insert_Success($this);
        }

		return $insertId;
    }
	
    public function updatePage($values = array())
    {
		if (!$this->have()) {
		    return ;
		}
		
		/** 插件接口 */
		//HOOK $values | PLUG_Page_Update($values, $this);
		
		$cid = $this->cid;

        /** 同步附件 */
        list($images, $files) = $this->widget('Widget_Attachs_Edit')->sync('page', $cid);
		$values['images'] = $images;
		$values['files'] = $files;

        /** 更新数据 */
        $updateRows = $this->update($cid, $values);
		
		$this->select()
		    ->where('table.contents.cid = ?', $cid)
			->limit(1)
			->fetchRow(array($this, 'push'));

        /** 插件接口 */
        //HOOK PLUG_Page_Update_Success($this);

		return $updateRows;
    }
    /**
     * 删除文章
     *
     * @access public
     * @return void
     */
    public function deletePage($cid)
    {

        $deleteRows = 0;

		/** 压入数据 */
		$content = $this->db->select()
		    ->from('table.contents')
			->where('cid = ?', $cid)
			->fetchRow(array($this, 'push'));

        /** 插件接口 */
        //HOOK PLUG_Page_Delete($this);
				
        if ($this->isWriteable() && 'page' == $this->type) {

            /** 更新内容数 */
		    $this->db->update('table.users')
		        ->where('uid = ?', $content['uid'])
				->expression('contentsNum', 'contentsNum - 1')
				->affectedRows();
				
			$Widget_Comments_Edit = $this->widget('Widget_Comments_Edit');
            while (1) {
                $arrlist = $this->db->select('coid')
				    ->from('table.comments')
			        ->where('cid = ?', $cid)
				    ->limit(1000)
				    ->fetchAll();
				
                if (empty($arrlist)) {
                    break;
                }

                foreach ($arrlist as $value) {
		            $Widget_Comments_Edit->deleteComment($value['coid']);
		        }
            }	

            /** 删除附件 */
            $this->widget('Widget_Attachs_Edit')->remove('page', $cid);
			
			/** 删除文章 */
			$deleteRows = $this->delete($cid);

            /** 插件接口 */
            //HOOK PLUG_Page_Delete_Success($this);
        }
		
		return $deleteRows;
    }
	
    public function operate()
    {
		$buttons = array();

		$buttons[] = Helper::element('a', _t('全选'), array(
		    'data-selectall'=>NULL,
			'href'=>'javascript:void(0);'
			)
		);

		$buttons[] = Helper::element('a', _t('删除'), array(
		    'href'=>'javascript:void(0);',
		    'data-action'=>$this->security->actionUrl('contents-page-edit?do=delete', false),
			'data-confirm'=>_t('删除不可恢复，确定删除？'),
			'data-item'=>'cid',
			'style'=>'color:red'
			)
		);

		/** 插件接口 */
		//HOOK $buttons[] | PLUG_Page_Operate($this);
		
		return $this->widget('Widget_Operate')->render($buttons);
    }	

    /**
     * 绑定动作
     *
     * @access public
     * @return void
     */
    public function action()
    {
        $this->security->protect();
		
        switch ($this->request->do) {
            case 'insert':
			
                $contents = array(
				    'title'         =>  $this->request->get('title', _t('未命名文档')),
			        'uid'           =>  $this->user->uid,
                    'commentsNum'   =>  0,
					'type'          =>  'page',
                    'allowComment'  =>  !empty($this->request->getArray('allowComment')) ? 1 : 0,
                    'intro'         =>  $this->autoIntro($this->request->intro, $this->request->text),
                );
                $contents += $this->request->from(array_keys($this->form()->getInputs()));

		        $this->insertPage($contents);
			
                /** 设置提示信息 */
                $this->result->set(0, _t('文章已经发布'), array('location'=>$this->options->ucenterUrl('pages?' . $this->getPageOffsetQuery($this->cid), false), 'cid'=>$this->theId));
				
            break;
            case 'update':

                $contents = array(
				    'title'         =>  $this->request->get('title', _t('未命名文档')),
                    'modified'      =>  $this->options->time,
                    'allowComment'  =>  !empty($this->request->getArray('allowComment')) ? 1 : 0,
                    'intro'         =>  $this->autoIntro($this->request->intro, $this->request->text),
                );
                $contents += $this->request->from(array_keys($this->form()->getInputs()));
		        $this->updatePage($contents);
			
                /** 设置提示信息 */
                $this->result->set(0, _t('文章更新成功'), array('location'=>$this->options->ucenterUrl('pages?' . $this->getPageOffsetQuery($this->cid), false), 'cid'=>$this->theId));
				
            break;

            case 'delete':
			
                $cids = $this->request->filter('int')->getArray('cid');
                $deleteRows = array();
                foreach ($cids as $cid) {
		            if($this->deletePage($cid)){ 
					    $deleteRows[] = $cid;
					}
		        }
			
                /** 设置提示信息 */
                $this->result->set(
				    $deleteRows ? 0 : 1, 
				    $deleteRows ? _t('成功删除 %s 篇文章', count($deleteRows)) : _t('没有文章被删除'),
				    $deleteRows
				);
				
            break;
        }
        $this->result->set(404, _t('请求的资源不存在'));
    }
}

